package JackSu.多线程;


import java.util.concurrent.locks.ReentrantLock;
/**
 * 方法三 jdk5新增
 * sychorlized自动释放同步监视器
 * lock方式需要自己手动启动和释放 同步锁
 */
class Window implements Runnable {
    private int ticket=100;

    private ReentrantLock lock = new ReentrantLock(true);

    @Override
    public void run() {

        while (true) {
            try {
                //   锁定方法lock
                lock.lock();

                if (ticket > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "票号为：" + ticket);
                    ticket--;
                } else {
                    break;
                }

            } finally {
                //解锁 unlock
                lock.unlock();
            }


        }


    }
}


public class _05Lock锁 {

    public static void main(String[] args) {

        Window w = new Window();
        Thread t1 = new Thread(w);
        Thread t2 = new Thread(w);
        Thread t3 = new Thread(w);
        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");
        t1.start();
        t2.start();
        t3.start();


    }


}
